package mrusanov.ui.battle

import javax.swing.{ JButton, JLabel, JPanel }
import net.miginfocom.swing.MigLayout
import mrusanov.battle.Battle
import mrusanov.localization.Localization
import java.awt.event.{ ActionEvent, ActionListener }
import java.awt.{ Color, Dimension }
import mrusanov.ai.StupidBattleAI
import mrusanov.util.swing.EventConsumer
import mrusanov.util.swing.Event
import mrusanov.tournament.MatchInfo
import javax.swing.JOptionPane

class BattleRightPanel(eventConsumer: EventConsumer[BattleResultPanel], battlePanel: BattlePanel, info: MatchInfo) extends JPanel {
	setLayout(new MigLayout())
	val battle = battlePanel.battle

	def hostLabelText = battle.hostTeam.name + " : " + battle.hostPoints
	def guestLabelText = battle.guestTeam.name + " : " + battle.guestPoints

	val hostLabel = new JLabel(hostLabelText)
	val guestLabel = new JLabel(guestLabelText)

	add(hostLabel, "wrap")
	add(guestLabel, "wrap")

	val nextTurnButton = new JButton(Localization("battle.nextTurn"))
	add(nextTurnButton, "dock south")

	nextTurnButton.addActionListener(new ActionListener {
		def actionPerformed(e: ActionEvent) {
			if (battle.isOver) {
				info.hostPoints = battle.hostPoints
				info.guestPoints = battle.guestPoints
				info.setOver()
				eventConsumer.consumeEvent(Event(new BattleResultPanel(battle)))
			} else {
				if (!battle.canBeTurnOver(battlePanel.userTeam)) {
					JOptionPane.showMessageDialog(null, Localization("battle.moveRequired.text"), Localization("battle.moveRequired.caption"),
						JOptionPane.WARNING_MESSAGE)
					return ;
				}

				val ai = new StupidBattleAI
				val aiTeam = if (battlePanel.userTeam == battle.hostTeam) battle.guestTeam
				else battle.hostTeam
				ai.makeTurn(battle, aiTeam)
				battlePanel.refresh()
				battlePanel.turnOver(battle.playRound())
			}
		}
	})

	def refresh() {
		guestLabel.setText(guestLabelText)
		hostLabel.setText(hostLabelText)
	}

}
